<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>智能对话助手 | 方舟API</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root {
            /* 颜色变量 */
            --primary: #4a76d0;
            --primary-light: #5e89e0;
            --primary-dark: #3a66c0;
            --secondary: #6c757d;
            --success: #28a745;
            --danger: #dc3545;
            --warning: #ffc107;
            --info: #17a2b8;
            --light: #f8f9fa;
            --dark: #343a40;
            --white: #ffffff;
            --gray-100: #f8f9fa;
            --gray-200: #e9ecef;
            --gray-300: #dee2e6;
            --gray-800: #343a40;
            --user-msg-bg: #e3f2fd;
            --ai-msg-bg: #f5f5f5;
            --user-msg-color: #1a73e8;
            --ai-msg-color: #5f6368;
            --sidebar-bg: #f8f9fa;
            --header-bg: #4a76d0;
            --input-bg: #ffffff;

            /* 阴影效果 */
            --shadow-sm: 0 1px 3px rgba(0, 0, 0, 0.12);
            --shadow-md: 0 4px 6px rgba(0, 0, 0, 0.1);
            --shadow-lg: 0 10px 15px rgba(0, 0, 0, 0.1);

            /* 圆角 */
            --border-radius: 12px;
            --border-radius-sm: 8px;
            --border-radius-lg: 16px;

            /* 过渡效果 */
            --transition: all 0.3s ease;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: var(--gray-800);
            line-height: 1.6;
            min-height: 100vh;
            padding: 20px;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .chat-app {
            width: 100%;
            max-width: 1200px;
            height: 90vh;
            background: var(--white);
            border-radius: var(--border-radius-lg);
            box-shadow: var(--shadow-lg);
            overflow: hidden;
            display: flex;
            transition: var(--transition);
        }

        /* ===== 侧边栏样式 ===== */
        .sidebar {
            width: 280px;
            background: var(--sidebar-bg);
            border-right: 1px solid var(--gray-300);
            display: flex;
            flex-direction: column;
            transition: var(--transition);
        }

        .sidebar-header {
            padding: 20px;
            background: var(--header-bg);
            color: var(--white);
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .sidebar-header h1 {
            font-size: 1.4rem;
            font-weight: 600;
        }

        .new-chat-btn {
            margin: 16px;
            padding: 12px 16px;
            background: var(--primary);
            color: var(--white);
            border: none;
            border-radius: var(--border-radius);
            font-weight: 500;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 8px;
            transition: var(--transition);
            box-shadow: var(--shadow-sm);
        }

        .new-chat-btn:hover {
            background: var(--primary-dark);
            transform: translateY(-2px);
            box-shadow: var(--shadow-md);
        }

        .history-list {
            flex: 1;
            overflow-y: auto;
            padding: 8px;
        }

        .history-item {
            padding: 12px 16px;
            border-radius: var(--border-radius);
            margin-bottom: 8px;
            cursor: pointer;
            transition: var(--transition);
            display: flex;
            align-items: center;
            justify-content: space-between;
            background: var(--white);
            box-shadow: var(--shadow-sm);
        }

        .history-item-content {
            display: flex;
            align-items: center;
            gap: 10px;
            flex: 1;
            overflow: hidden;
        }

        .history-item-title {
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            font-weight: 500;
        }

        .history-item:hover {
            background: var(--gray-200);
            transform: translateY(-1px);
            box-shadow: var(--shadow-md);
        }

        .history-item.active {
            background: var(--primary-light);
            color: var(--white);
        }

        .history-item-time {
            font-size: 0.75rem;
            color: var(--secondary);
            margin-top: 4px;
        }

        .delete-btn {
            background: none;
            border: none;
            color: var(--secondary);
            cursor: pointer;
            padding: 4px;
            border-radius: 4px;
            opacity: 0.6;
            transition: var(--transition);
        }

        .delete-btn:hover {
            color: var(--danger);
            opacity: 1;
        }

        .sidebar-footer {
            padding: 16px;
            border-top: 1px solid var(--gray-300);
        }

        .user-profile {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: var(--primary);
            color: var(--white);
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            box-shadow: var(--shadow-sm);
        }

        .user-info {
            flex: 1;
        }

        .user-name {
            font-weight: 500;
        }

        .user-status {
            font-size: 0.8rem;
            color: var(--secondary);
        }

        /* ===== 主聊天区域样式 ===== */
        .chat-main {
            flex: 1;
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }

        .chat-header {
            padding: 16px 24px;
            border-bottom: 1px solid var(--gray-300);
            display: flex;
            align-items: center;
            justify-content: space-between;
            background: var(--white);
        }

        .chat-title {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .chat-title h2 {
            font-size: 1.4rem;
            font-weight: 600;
        }

        .header-actions {
            display: flex;
            gap: 12px;
        }

        .icon-btn {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            background: transparent;
            border: none;
            color: var(--secondary);
            cursor: pointer;
            transition: var(--transition);
        }

        .icon-btn:hover {
            background: var(--gray-200);
            color: var(--primary);
        }

        .chat-messages {
            flex: 1;
            overflow-y: auto;
            padding: 24px;
            background: var(--white);
            display: flex;
            flex-direction: column;
            gap: 16px;
        }

        .message {
            max-width: 70%;
            display: flex;
            gap: 12px;
            animation: fadeIn 0.3s ease;
        }

        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: translateY(10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .message.user {
            align-self: flex-end;
            flex-direction: row-reverse;
        }

        .message-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            flex-shrink: 0;
            box-shadow: var(--shadow-sm);
        }

        .user .message-avatar {
            background: var(--primary);
            color: var(--white);
        }

        .ai .message-avatar {
            background: var(--gray-300);
            color: var(--gray-800);
        }

        .message-content {
            display: flex;
            flex-direction: column;
            gap: 6px;
        }

        .message-bubble {
            padding: 12px 16px;
            border-radius: 18px;
            box-shadow: var(--shadow-sm);
            transition: var(--transition);
        }

        .user .message-bubble {
            background: var(--user-msg-bg);
            color: var(--user-msg-color);
            border-bottom-right-radius: 4px;
        }

        .ai .message-bubble {
            background: var(--ai-msg-bg);
            color: var(--ai-msg-color);
            border-bottom-left-radius: 4px;
        }

        .message-time {
            font-size: 0.75rem;
            color: var(--secondary);
            padding: 0 8px;
        }

        .user .message-time {
            text-align: right;
        }

        .thinking-indicator {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 12px 16px;
            background: var(--ai-msg-bg);
            border-radius: 18px;
            border-bottom-left-radius: 4px;
            max-width: 120px;
            color: var(--ai-msg-color);
            animation: pulse 1.5s infinite;
        }

        @keyframes pulse {
            0%, 100% {
                opacity: 0.6;
            }
            50% {
                opacity: 1;
            }
        }

        .typing-animation {
            display: flex;
            gap: 4px;
        }

        .typing-dot {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background: var(--ai-msg-color);
            animation: typingAnimation 1.4s infinite ease-in-out;
        }

        .typing-dot:nth-child(1) { animation-delay: 0s; }
        .typing-dot:nth-child(2) { animation-delay: 0.2s; }
        .typing-dot:nth-child(3) { animation-delay: 0.4s; }

        @keyframes typingAnimation {
            0%, 60%, 100% {
                transform: translateY(0);
                opacity: 0.4;
            }
            30% {
                transform: translateY(-5px);
                opacity: 1;
            }
        }

        .chat-input-area {
            padding: 20px;
            border-top: 1px solid var(--gray-300);
            background: var(--input-bg);
        }

        .input-container {
            display: flex;
            gap: 12px;
            align-items: flex-end;
        }

        .message-input {
            flex: 1;
            padding: 14px 16px;
            border: 1px solid var(--gray-300);
            border-radius: 24px;
            font-size: 1rem;
            outline: none;
            resize: none;
            max-height: 120px;
            transition: var(--transition);
            font-family: inherit;
            background: var(--white);
        }

        .message-input:focus {
            border-color: var(--primary);
            box-shadow: 0 0 0 2px rgba(74, 118, 208, 0.2);
        }

        .send-btn {
            width: 48px;
            height: 48px;
            border-radius: 50%;
            background: var(--primary);
            color: var(--white);
            border: none;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: var(--transition);
            box-shadow: var(--shadow-sm);
        }

        .send-btn:hover:not(:disabled) {
            background: var(--primary-dark);
            transform: scale(1.05);
            box-shadow: var(--shadow-md);
        }

        .send-btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
        }

        .input-actions {
            display: flex;
            justify-content: space-between;
            margin-top: 12px;
        }

        .action-buttons {
            display: flex;
            gap: 8px;
        }

        .action-btn {
            padding: 8px 16px;
            border: 1px solid var(--gray-300);
            border-radius: 20px;
            background: var(--white);
            color: var(--secondary);
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 6px;
            font-size: 0.9rem;
            transition: var(--transition);
        }

        .action-btn:hover {
            background: var(--gray-100);
            color: var(--primary);
        }

        .model-info {
            font-size: 0.85rem;
            color: var(--secondary);
            display: flex;
            align-items: center;
            gap: 6px;
        }

        /* ===== 响应式设计 ===== */
        @media (max-width: 768px) {
            .chat-app {
                flex-direction: column;
                height: 95vh;
            }

            .sidebar {
                width: 100%;
                height: auto;
                max-height: 40%;
                border-right: none;
                border-bottom: 1px solid var(--gray-300);
            }

            .message {
                max-width: 85%;
            }
        }

        /* ===== 滚动条样式 ===== */
        ::-webkit-scrollbar {
            width: 8px;
        }

        ::-webkit-scrollbar-track {
            background: var(--gray-100);
            border-radius: 4px;
        }

        ::-webkit-scrollbar-thumb {
            background: var(--gray-300);
            border-radius: 4px;
        }

        ::-webkit-scrollbar-thumb:hover {
            background: var(--secondary);
        }

        /* ===== 通知样式 ===== */
        .notification {
            position: fixed;
            bottom: 20px;
            right: 20px;
            padding: 12px 20px;
            border-radius: var(--border-radius);
            background: var(--white);
            box-shadow: var(--shadow-lg);
            display: flex;
            align-items: center;
            gap: 10px;
            z-index: 1000;
            transform: translateY(100px);
            opacity: 0;
            transition: transform 0.3s ease, opacity 0.3s ease;
        }

        .notification.show {
            transform: translateY(0);
            opacity: 1;
        }

        .notification.success {
            border-left: 4px solid var(--success);
        }

        .notification.error {
            border-left: 4px solid var(--danger);
        }

        .notification.warning {
            border-left: 4px solid var(--warning);
        }

        .notification-icon {
            font-size: 1.2rem;
        }

        .success .notification-icon {
            color: var(--success);
        }

        .error .notification-icon {
            color: var(--danger);
        }

        .warning .notification-icon {
            color: var(--warning);
        }

        .notification-content {
            flex: 1;
        }

        .notification-title {
            font-weight: 500;
            margin-bottom: 4px;
        }

        .notification-message {
            font-size: 0.9rem;
            color: var(--secondary);
        }

        .notification-close {
            background: none;
            border: none;
            color: var(--secondary);
            cursor: pointer;
            font-size: 1.1rem;
        }
    </style>
</head>
<body>
    <div class="chat-app">
        <!-- 侧边栏 -->
        <div class="sidebar">
            <div class="sidebar-header">
                <i class="fas fa-robot"></i>
                <h1>智能对话助手</h1>
            </div>

            <button class="new-chat-btn" id="new-chat-btn">
                <i class="fas fa-plus"></i>
                新建对话
            </button>

            <div class="history-list" id="history-list">
                <!-- 历史对话将动态加载 -->
            </div>

            <div class="sidebar-footer">
                <div class="user-profile">
                    <div class="avatar">U</div>
                    <div class="user-info">
                        <div class="user-name">用户</div>
                        <div class="user-status">在线</div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 主聊天区域 -->
        <div class="chat-main">
            <div class="chat-header">
                <div class="chat-title">
                    <i class="fas fa-comments"></i>
                    <h2 id="current-chat-title">智能对话</h2>
                </div>
                <div class="header-actions">
                    <button class="icon-btn" id="refresh-btn" title="刷新会话列表">
                        <i class="fas fa-sync-alt"></i>
                    </button>
                    <button class="icon-btn" id="export-btn" title="导出当前对话">
                        <i class="fas fa-download"></i>
                    </button>
                </div>
            </div>

            <div class="chat-messages" id="chat-messages">
                <div class="message ai">
                    <div class="message-avatar">AI</div>
                    <div class="message-content">
                        <div class="message-bubble">
                            您好！我是智能对话助手，基于方舟API和Transformer技术构建。有什么我可以帮助您的吗？
                        </div>
                        <div class="message-time" id="current-time"></div>
                    </div>
                </div>
            </div>

            <div class="chat-input-area">
                <div class="input-container">
                    <textarea class="message-input" id="message-input" placeholder="输入消息..." rows="1"></textarea>
                    <button class="send-btn" id="send-btn" title="发送消息">
                        <i class="fas fa-paper-plane"></i>
                    </button>
                </div>
                <div class="input-actions">
                    <div class="action-buttons">
                        <button class="action-btn" id="reset-btn">
                            <i class="fas fa-redo"></i>
                            重置
                        </button>
                        <button class="action-btn" id="export-chat-btn">
                            <i class="fas fa-download"></i>
                            导出
                        </button>
                    </div>
                    <div class="model-info">
                        <i class="fas fa-microchip"></i>
                        模型: deepseek-v3-1-250821
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 通知组件 -->
    <div class="notification" id="notification">
        <div class="notification-icon">
            <i class="fas fa-info-circle"></i>
        </div>
        <div class="notification-content">
            <div class="notification-title" id="notification-title">通知标题</div>
            <div class="notification-message" id="notification-message">通知内容</div>
        </div>
        <button class="notification-close" id="notification-close">
            <i class="fas fa-times"></i>
        </button>
    </div>

    <script>
        // ===== DOM元素 =====
        const messageInput = document.getElementById('message-input');
        const sendBtn = document.getElementById('send-btn');
        const resetBtn = document.getElementById('reset-btn');
        const exportBtn = document.getElementById('export-btn');
        const exportChatBtn = document.getElementById('export-chat-btn');
        const newChatBtn = document.getElementById('new-chat-btn');
        const refreshBtn = document.getElementById('refresh-btn');
        const chatMessages = document.getElementById('chat-messages');
        const historyList = document.getElementById('history-list');
        const currentChatTitle = document.getElementById('current-chat-title');
        const currentTime = document.getElementById('current-time');
        const notification = document.getElementById('notification');
        const notificationTitle = document.getElementById('notification-title');
        const notificationMessage = document.getElementById('notification-message');
        const notificationClose = document.getElementById('notification-close');

        // ===== 状态变量 =====
        let isGenerating = false;
        let currentSessionId = null;
        let notificationTimeout = null;

        // ===== 初始化 =====
        function init() {
            updateCurrentTime();
            setInterval(updateCurrentTime, 60000); // 每分钟更新一次时间

            loadSessions();
            messageInput.focus();

            // 绑定通知关闭事件
            notificationClose.addEventListener('click', hideNotification);
        }

        // ===== 通知系统 =====
        function showNotification(type, title, message, duration = 3000) {
            // 清除之前的通知
            hideNotification();

            // 设置通知内容
            notificationTitle.textContent = title;
            notificationMessage.textContent = message;

            // 设置通知类型
            notification.className = 'notification';
            notification.classList.add(type);
            notification.classList.add('show');

            // 自动隐藏通知
            if (duration > 0) {
                notificationTimeout = setTimeout(hideNotification, duration);
            }
        }

        function hideNotification() {
            notification.classList.remove('show');
            if (notificationTimeout) {
                clearTimeout(notificationTimeout);
                notificationTimeout = null;
            }
        }

        // ===== 时间管理 =====
        function updateCurrentTime() {
            const now = new Date();
            currentTime.textContent = now.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
        }

        // ===== 会话管理 =====
        async function loadSessions() {
            try {
                const response = await fetch('/api/sessions');
                if (!response.ok) {
                    throw new Error(`HTTP错误: ${response.status}`);
                }

                const data = await response.json();
                if (!data.success) {
                    throw new Error(data.message || '加载会话失败');
                }

                renderSessions(data.data.sessions);

                // 如果没有当前会话，创建新会话
                if (data.data.sessions.length === 0) {
                    await createNewSession();
                } else if (!currentSessionId) {
                    // 加载最新的会话
                    await loadSession(data.data.sessions[0].id);
                }
            } catch (error) {
                console.error('加载会话失败:', error);
                showNotification('error', '加载失败', error.message);
            }
        }

        function renderSessions(sessions) {
            historyList.innerHTML = '';

            sessions.forEach(session => {
                const sessionItem = document.createElement('div');
                sessionItem.className = `history-item ${session.id === currentSessionId ? 'active' : ''}`;
                sessionItem.innerHTML = `
                    <div class="history-item-content">
                        <i class="fas fa-comment"></i>
                        <div>
                            <div class="history-item-title">${session.title}</div>
                            <div class="history-item-time">${formatTime(session.last_active)}</div>
                        </div>
                    </div>
                    <button class="delete-btn" data-session-id="${session.id}" title="删除会话">
                        <i class="fas fa-trash"></i>
                    </button>
                `;

                sessionItem.addEventListener('click', (e) => {
                    if (!e.target.closest('.delete-btn')) {
                        loadSession(session.id);
                    }
                });

                // 添加删除按钮事件
                const deleteBtn = sessionItem.querySelector('.delete-btn');
                deleteBtn.addEventListener('click', (e) => {
                    e.stopPropagation();
                    deleteSession(session.id);
                });

                historyList.appendChild(sessionItem);
            });
        }

        function formatTime(isoString) {
            const date = new Date(isoString);
            return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
        }

        async function deleteSession(sessionId) {
            if (!confirm('确定要删除这个对话吗？此操作不可撤销。')) {
                return;
            }

            try {
                const response = await fetch(`/api/sessions/${sessionId}`, {
                    method: 'DELETE'
                });

                const data = await response.json();
                if (!data.success) {
                    throw new Error(data.message || '删除会话失败');
                }

                // 如果删除的是当前会话，创建新会话
                if (currentSessionId === sessionId) {
                    await createNewSession();
                }

                await loadSessions();
                showNotification('success', '删除成功', '会话已成功删除');
            } catch (error) {
                console.error('删除会话失败:', error);
                showNotification('error', '删除失败', error.message);
            }
        }

        async function createNewSession() {
            try {
                const response = await fetch('/api/sessions', {
                    method: 'POST'
                });

                if (!response.ok) {
                    throw new Error(`HTTP错误: ${response.status}`);
                }

                const data = await response.json();
                if (!data.success) {
                    throw new Error(data.message || '创建会话失败');
                }

                currentSessionId = data.data.session_id;
                await loadSessions();
                clearChatMessages();
                addWelcomeMessage();
                showNotification('success', '创建成功', '新会话已创建');
            } catch (error) {
                console.error('创建会话失败:', error);
                showNotification('error', '创建失败', error.message);
            }
        }

        async function loadSession(sessionId) {
            try {
                const response = await fetch(`/api/sessions/${sessionId}`);
                if (!response.ok) {
                    throw new Error(`HTTP错误: ${response.status}`);
                }

                const data = await response.json();
                if (!data.success) {
                    throw new Error(data.message || '加载会话失败');
                }

                currentSessionId = sessionId;
                currentChatTitle.textContent = data.data.title;

                // 清空当前消息并重新渲染
                clearChatMessages();
                renderMessages(data.data.messages.slice(1)); // 排除系统消息

                // 更新会话列表高亮
                await loadSessions();
            } catch (error) {
                console.error('加载会话失败:', error);
                showNotification('error', '加载失败', error.message);
            }
        }

        // ===== 消息管理 =====
        function clearChatMessages() {
            chatMessages.innerHTML = '';
        }

        function renderMessages(messages) {
            messages.forEach(msg => {
                if (msg.role === 'user' || msg.role === 'assistant') {
                    addMessage(msg.role, msg.content, false);
                }
            });
        }

        function addWelcomeMessage() {
            const welcomeMsg = "您好！我是智能对话助手，基于方舟API和Transformer技术构建。有什么我可以帮助您的吗？";
            addMessage('ai', welcomeMsg, false);
        }

        function addMessage(role, content, isStreaming = false) {
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${role}`;

            const avatar = role === 'user' ? 'U' : 'AI';
            const time = new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });

            messageDiv.innerHTML = `
                <div class="message-avatar">${avatar}</div>
                <div class="message-content">
                    <div class="message-bubble">${isStreaming ? content + '<span class="typing-cursor"></span>' : content}</div>
                    <div class="message-time">${time}</div>
                </div>
            `;

            chatMessages.appendChild(messageDiv);
            chatMessages.scrollTop = chatMessages.scrollHeight;

            return messageDiv.querySelector('.message-bubble');
        }

        function addThinkingIndicator() {
            const thinkingDiv = document.createElement('div');
            thinkingDiv.className = 'thinking-indicator';
            thinkingDiv.innerHTML = `
                <div class="typing-animation">
                    <div class="typing-dot"></div>
                    <div class="typing-dot"></div>
                    <div class="typing-dot"></div>
                </div>
                <span>思考中</span>
            `;
            chatMessages.appendChild(thinkingDiv);
            chatMessages.scrollTop = chatMessages.scrollHeight;
            return thinkingDiv;
        }

        // ===== 消息发送 =====
        async function sendMessage() {
            const message = messageInput.value.trim();
            if (!message || isGenerating) return;

            isGenerating = true;
            sendBtn.disabled = true;
            messageInput.disabled = true;

            // 添加到界面
            addMessage('user', message);
            messageInput.value = '';
            messageInput.style.height = 'auto';

            // 显示思考指示器
            const thinkingIndicator = addThinkingIndicator();

            try {
                const aiMessageElement = addMessage('ai', '', true);
                let aiResponse = '';

                const response = await fetch('/api/chat/stream', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ message })
                });

                if (!response.ok) {
                    throw new Error(`HTTP错误: ${response.status}`);
                }

                const reader = response.body.getReader();
                const decoder = new TextDecoder();

                while (true) {
                    const { value, done } = await reader.read();
                    if (done) break;

                    const content = decoder.decode(value, { stream: true });
                    if (content) {
                        aiResponse += content;
                        aiMessageElement.innerHTML = aiResponse + '<span class="typing-cursor"></span>';
                        chatMessages.scrollTop = chatMessages.scrollHeight;
                    }
                }

                aiMessageElement.innerHTML = aiResponse;

                // 重新加载会话列表以更新标题
                await loadSessions();

            } catch (error) {
                const errorMsg = `错误: ${error.message}`;
                addMessage('ai', errorMsg);
                showNotification('error', '发送失败', error.message);
            } finally {
                thinkingIndicator.remove();
                isGenerating = false;
                sendBtn.disabled = false;
                messageInput.disabled = false;
                messageInput.focus();
            }
        }

        // ===== 操作功能 =====
        async function resetConversation() {
            if (isGenerating) return;

            try {
                const response = await fetch('/api/sessions/current/reset', {
                    method: 'POST'
                });

                if (!response.ok) {
                    throw new Error(`HTTP错误: ${response.status}`);
                }

                const data = await response.json();
                if (!data.success) {
                    throw new Error(data.message || '重置失败');
                }

                clearChatMessages();
                addWelcomeMessage();
                showNotification('success', '重置成功', '对话已重置');
            } catch (error) {
                showNotification('error', '重置失败', error.message);
            }
        }

        async function exportConversation() {
            try {
                const response = await fetch('/api/export');
                if (!response.ok) {
                    throw new Error(`HTTP错误: ${response.status}`);
                }

                const data = await response.json();
                if (!data.success) {
                    throw new Error(data.message || '导出失败');
                }

                const exportData = data.data;
                const dataStr = JSON.stringify(exportData, null, 2);
                const dataUri = 'data:application/json;charset=utf-8,'+ encodeURIComponent(dataStr);

                const exportFileDefaultName = `chat_export_${new Date().toISOString().slice(0, 10)}.json`;

                const linkElement = document.createElement('a');
                linkElement.setAttribute('href', dataUri);
                linkElement.setAttribute('download', exportFileDefaultName);
                linkElement.click();

                showNotification('success', '导出成功', '对话已导出为JSON文件');
            } catch (error) {
                showNotification('error', '导出失败', error.message);
            }
        }

        async function refreshSessions() {
            try {
                await loadSessions();
                showNotification('success', '刷新成功', '会话列表已更新');
            } catch (error) {
                showNotification('error', '刷新失败', error.message);
            }
        }

        // ===== 事件监听 =====
        sendBtn.addEventListener('click', sendMessage);
        resetBtn.addEventListener('click', resetConversation);
        exportChatBtn.addEventListener('click', exportConversation);
        exportBtn.addEventListener('click', exportConversation);
        newChatBtn.addEventListener('click', createNewSession);
        refreshBtn.addEventListener('click', refreshSessions);

        messageInput.addEventListener('keydown', (e) => {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                sendMessage();
            }
        });

        // 自动调整文本区域高度
        messageInput.addEventListener('input', function() {
            this.style.height = 'auto';
            this.style.height = (this.scrollHeight) + 'px';
        });

        // 初始化应用
        init();
    </script>
</body>
</html>